﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Caching.Distributed;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using KAsFrame.Common.Dto;
using Microsoft.AspNetCore.Mvc;
using KAsFrame.Common.Extensions;
using Microsoft.AspNetCore.Authorization;

namespace KAsFrame.Common.Filter
{
    /// <summary>
    /// 已在startup中注册至所有action，非鉴权接口应添加特性AllowAnonymousFilter
    /// </summary>
    public class ApiAuthorFilter : IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            if (context.ActionDescriptor.EndpointMetadata.Any(x => x.GetType() == typeof(AllowAnonymousAttribute)))
                return;

            var cache = context.HttpContext.RequestServices.GetService<IDistributedCache>();
            if (!context.HttpContext.Request.Headers.ContainsKey("token"))
            {
                context.Result = new JsonResult(ApiResult<string>.IsError("当前请求未授权", code: "401")) { StatusCode = 401 };
                return;
            }

            var token = context.HttpContext.Request.Headers["token"].ToString();
            var cacheToken = cache.Get<UserInfoDto>($"token:{token}");
            if (cacheToken == null)
            {
                context.Result = new JsonResult(ApiResult<string>.IsError("未登录或登录超时，请重新登录", code: "401")) { StatusCode = 401 };
                return;
            }
            else
            {
                // 重置超时时间
                cache.Refresh($"token:{token}");
            }
        }
    }
}
